package com.itic.mall.system.order.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.mall.system.cert.persistence.dao.CertDao;
import com.itic.mall.system.cert.persistence.model.Cert;
import com.itic.mall.system.cert.persistence.model.CertExample;
import com.itic.mall.system.certproduct.persistence.dao.CertProductDao;
import com.itic.mall.system.certproduct.persistence.model.CertProduct;
import com.itic.mall.system.certproduct.persistence.model.CertProductExample;
import com.itic.mall.system.certproduct.persistence.model.CertProductExample.Criteria;
import com.itic.mall.system.expendlog.persistence.dao.ExpendLogDao;
import com.itic.mall.system.expendlog.persistence.model.ExpendLog;
import com.itic.mall.system.hongbaorecord.persistence.dao.HongbaoRecordDao;
import com.itic.mall.system.hongbaorecord.persistence.model.HongbaoRecord;
import com.itic.mall.system.hongbaorecord.persistence.model.HongbaoRecordExample;
import com.itic.mall.system.incomelog.persistence.dao.IncomeLogDao;
import com.itic.mall.system.incomelog.persistence.model.IncomeLog;
import com.itic.mall.system.jifeng.persistence.dao.JifengDao;
import com.itic.mall.system.jifeng.persistence.model.Jifeng;
import com.itic.mall.system.marketprofit.persistence.dao.MarketProfitDao;
import com.itic.mall.system.marketprofit.persistence.model.MarketProfit;
import com.itic.mall.system.marketuser.persistence.dao.MarketUserDao;
import com.itic.mall.system.marketuser.persistence.model.MarketUser;
import com.itic.mall.system.marketuserproduct.persistence.dao.MarketUserProductDao;
import com.itic.mall.system.marketuserproduct.persistence.model.MarketUserProduct;
import com.itic.mall.system.order.persistence.dao.OrderDao;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.persistence.model.OrderExample;
import com.itic.mall.system.orderexpress.persistence.dao.OrderExpressDao;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpress;
import com.itic.mall.system.orderpay.persistence.dao.OrderPayDao;
import com.itic.mall.system.orderpay.persistence.model.OrderPay;
import com.itic.mall.system.orderproducts.persistence.dao.OrderProductsDao;
import com.itic.mall.system.orderproducts.persistence.model.OrderProducts;
import com.itic.mall.system.paymoney.persistence.dao.PayMoneyDao;
import com.itic.mall.system.paymoney.persistence.model.PayMoney;
import com.itic.mall.system.premoney.persistence.dao.PreMoneyDao;
import com.itic.mall.system.premoney.persistence.model.PreMoney;
import com.itic.mall.system.premoney.persistence.model.PreMoneyExample;
import com.itic.mall.system.product.persistence.dao.ProductDao;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.productsku.persistence.dao.ProductSkuDao;
import com.itic.mall.system.productsku.persistence.model.ProductSku;
import com.itic.mall.system.profitmoney.persistence.dao.ProfitMoneyDao;
import com.itic.mall.system.profitmoney.persistence.model.ProfitMoney;
import com.itic.mall.system.statis.persistence.dao.StatisDao;
import com.itic.mall.system.statis.persistence.model.Statis;
import com.itic.mall.system.user.persistence.dao.MallUserDao;
import com.itic.mall.system.user.persistence.model.MallUser;


@Service
@Transactional
public class OrderService
     extends CrudService<OrderDao,Order,OrderExample> {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderProductsDao orderProductsDao;
    @Autowired
    private MarketUserDao marketUserDao;
    @Autowired
    private MallUserDao mallUserDao;
    @Autowired
    private JifengDao jifengDao;
    @Autowired
    private PreMoneyDao preMoneyDao;
    @Autowired
    private OrderPayDao orderPayDao;
    @Autowired
    private IncomeLogDao incomeLogDao;
    @Autowired
    private StatisDao statisDao;
    @Autowired
    private ExpendLogDao expendLogDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private ProductSkuDao productSkuDao;
    @Autowired
    private PayMoneyDao payMoneyDao;
    @Autowired
    private OrderExpressDao orderExpressDao;
    @Autowired
    private MarketProfitDao marketProfitDao;
    @Autowired
    private CertProductDao certProductDao;
    @Autowired
    private CertDao certDao;
    @Autowired
    private HongbaoRecordDao hongbaoRecordDao;
    @Autowired
    private MarketUserProductDao marketUserProductDao;
    @Autowired
    private ProfitMoneyDao profitMoneyDao;

	public String createOrder(Order order, List<OrderProducts> orderProducts) {
		orderDao.insertSelective(order);
		ArrayList<String> ids = new ArrayList<String>();
		for( OrderProducts temp : orderProducts ){
			orderProductsDao.insertSelective(temp);
			ids.add(temp.getPropertySkuId());
		}
		//删除购物车的信息
		CertProductExample example = new CertProductExample();
		Criteria criteria = example.createCriteria().andUserIdEqualTo(order.getUserId());
		criteria.andProductSkuIdIn(ids);
		certProductDao.deleteByExample(example);
		//重置购物的数量和总价格
		resetCert(order.getUserId());
		return SUCCESS;
	}

	public String confirm(Order order, OrderProducts orderProducts) {
		if(null!=order){
			orderDao.updateByPrimaryKeySelective(order);
		}
		orderProductsDao.updateByPrimaryKeySelective(orderProducts);
		return SUCCESS;
	}

	public String paySuccess(List<MarketUser> marketUsers,
			List<PreMoney> preMoneys, Order order,List<OrderProducts> products,OrderPay orderPay, IncomeLog incomeLog,
			Statis statis) {
		if( null != marketUsers ){
			if( marketUsers.size() > 0 ){
				for( MarketUser temp : marketUsers ){
					marketUserDao.updateByPrimaryKeySelective(temp);
				}
			}
		}
		if( null != preMoneys ){
			if( preMoneys.size() > 0 ){
				for( PreMoney temp : preMoneys ){
					preMoneyDao.insert(temp);
				}
			}
		}
		if( null != products ){
			if( products.size() > 0 ){
				for( OrderProducts temp : products ){
					orderProductsDao.updateByPrimaryKeySelective(temp);
				}
			}
		}
		orderDao.updateByPrimaryKeySelective(order);
		orderPayDao.insert(orderPay);
		incomeLogDao.insert(incomeLog);
		statisDao.insertSelective(statis);
		return SUCCESS;
	}
	
	public String paySuccessV2(List<MarketUser> marketUsers,
			List<PreMoney> preMoneys, Order order,List<OrderProducts> products,OrderPay orderPay,MallUser user,Jifeng jifeng) {
		if( null != marketUsers ){
			if( marketUsers.size() > 0 ){
				for( MarketUser temp : marketUsers ){
					marketUserDao.updateByPrimaryKeySelective(temp);
				}
			}
		}
		if( null != preMoneys ){
			if( preMoneys.size() > 0 ){
				for( PreMoney temp : preMoneys ){
					preMoneyDao.insert(temp);
				}
			}
		}
		if( null != products ){
			if( products.size() > 0 ){
				for( OrderProducts temp : products ){
					orderProductsDao.updateByPrimaryKeySelective(temp);
				}
			}
		}
		orderDao.updateByPrimaryKeySelective(order);
		orderPayDao.insert(orderPay);
		mallUserDao.updateByPrimaryKey(user);
		jifengDao.updateByPrimaryKey(jifeng);
		//incomeLogDao.insert(incomeLog);
		//statisDao.insertSelective(statis);
		return SUCCESS;
	}

	public String confirm(OrderProducts orderProducts, Product product,
			Order order, PreMoney preMoney, PayMoney payMoney,
			MarketUser marketUser, Statis statis, ExpendLog expendLog) {
		
		if( null != orderProducts ){
			orderProductsDao.updateByPrimaryKeySelective(orderProducts);
		}
		if( null != product ){
			productDao.updateByPrimaryKeySelective(product);
		}
		if( null != order ){
			orderDao.updateByPrimaryKeySelective(order);
		}
		if( null != preMoney ){
			preMoneyDao.updateByPrimaryKeySelective(preMoney);
		}
		
		if( null != payMoney ){
			payMoneyDao.updateByPrimaryKeySelective(payMoney);
		}
		if( null != marketUser ){
			marketUserDao.updateByPrimaryKeySelective(marketUser);
		}
		if( null != statis ){
			statisDao.updateByPrimaryKeySelective(statis);
		}
		if( null != expendLog ){
			expendLogDao.updateByPrimaryKeySelective(expendLog);
		}
		
		return SUCCESS;
	}

	
	public String comebackExpress(OrderProducts orderProducts,
			OrderExpress orderPress) {
		orderProductsDao.updateByPrimaryKeySelective(orderProducts);
		orderExpressDao.insert(orderPress);
		return SUCCESS;
	}

	public String confirm(OrderProducts orderProducts, Product product,
			Order order, PreMoney preMoney, PayMoney payMoney,
			List<MarketUser> marketUsers, List<Statis> statiss,
			List<ExpendLog> expendLogs, List<MarketProfit> marketProfits , MarketUserProduct marketUserProduct ) {
		if( null != orderProducts ){
			orderProductsDao.updateByPrimaryKeySelective(orderProducts);
		}
		if( null != product ){
			productDao.updateByPrimaryKeySelective(product);
		}
		if( null != order ){
			orderDao.updateByPrimaryKeySelective(order);
		}
		if( null != preMoney ){
			preMoneyDao.updateByPrimaryKeySelective(preMoney);
		}
		
		if( null != payMoney ){
			payMoneyDao.insert(payMoney);
		}
		
		if( null != marketUsers && marketUsers.size() > 0 ){
			for( MarketUser tmp : marketUsers ){
				marketUserDao.updateByPrimaryKeySelective(tmp);
			}
		}
		if( null != statiss && statiss.size() > 0 ){
			for( Statis tmp : statiss ){
				statisDao.insert(tmp);
			}
		}
		if( null != expendLogs && expendLogs.size() > 0  ){
			for( ExpendLog tmp : expendLogs ){
				expendLogDao.insert(tmp);
			}
		}
		if( null != marketProfits && marketProfits.size() > 0 ){
			for( MarketProfit tmp : marketProfits ){
				marketProfitDao.insert(tmp);
			}
		}
		if( null != marketUserProduct ){
			marketUserProductDao.updateByPrimaryKeySelective(marketUserProduct);
		}
		return SUCCESS;
	}
	
	public String confirmV2(OrderProducts orderProducts, Product product,
			Order order, PreMoney preMoney, PayMoney payMoney,
			List<MarketUser> marketUsers, MarketUserProduct marketUserProduct, List<ProfitMoney> profitMoneys) {
		if( null != orderProducts ){
			orderProductsDao.updateByPrimaryKeySelective(orderProducts);
		}
		if( null != product ){
			productDao.updateByPrimaryKeySelective(product);
		}
		if( null != order ){
			orderDao.updateByPrimaryKeySelective(order);
		}
		if( null != preMoney ){
			preMoneyDao.updateByPrimaryKeySelective(preMoney);
		}
		
		if( null != payMoney ){
			payMoneyDao.insert(payMoney);
		}
		
		if( null != marketUsers && marketUsers.size() > 0 ){
			for( MarketUser tmp : marketUsers ){
				marketUserDao.updateByPrimaryKeySelective(tmp);
			}
		}
		if( null != marketUserProduct ){
			marketUserProductDao.updateByPrimaryKeySelective(marketUserProduct);
		}
		if( null != profitMoneys && profitMoneys.size() > 0 ){
			for( ProfitMoney tmp : profitMoneys ){
				profitMoneyDao.insert(tmp);
			}
		}
		return SUCCESS;
	}
	
	/*
	 * 重置购物车信息
	 */
	public void resetCert(String userId){
		  Cert cert = null;
	      CertExample example = new CertExample();
	      example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andUserIdEqualTo(userId);
	      List<Cert> list = certDao.selectByExample(example);
	      if( list.size() > 0 ){
	   	     cert = list.get(0);
	   	     String totalCount="0";
		     String totalMoney="0";
		     CertProductExample example1 = new CertProductExample();
		     Criteria criteria = example1.createCriteria();
		     criteria.andIsEffectiveEqualTo(DBConst.TRUE).andCertIdEqualTo(cert.getId());
		     List<CertProduct> list1 = certProductDao.selectByExample(example1);
		     if( list.size() > 0 ){
			   for( CertProduct tmp : list1 ){
				   String productSkuId = tmp.getProductSkuId();
				   ProductSku sku = productSkuDao.selectByPrimaryKey(productSkuId);
				   Product product = productDao.selectByPrimaryKey(sku.getProductId());
				   String productCount = tmp.getProductCount();
				   String price = sku.getProductOrginPrice();
				   String haveHongbao = isHaveHongbao(cert.getUserId(),sku.getProductId());
				   if( "1".equals(haveHongbao) ){
					   price= NumberStringHelper.subtractString(sku.getProductOrginPrice(), product.getProductHongbao());
				   }
				   
				   String tempTotalMoney = NumberStringHelper.mulString(productCount, price);
				   totalMoney = NumberStringHelper.addString(tempTotalMoney, totalMoney);
				   
				   totalCount = NumberStringHelper.addString(productCount, totalCount);
			   }
		    }
		    
		    cert.setTotalMoney(totalMoney);
		    cert.setTotalCount(totalCount);
		    certDao.updateByPrimaryKey(cert);
	      }
		   
	}
	
	
	/**
     * 用户是否领取过红包 
     * @param userId
     * @param productId
     * @return
     */
    public String isHaveHongbao( String userId, String productId ){
    	String result = "0";
    	Product product = productDao.selectByPrimaryKey(productId);
    	if( null != product ){
    		HongbaoRecordExample example = new HongbaoRecordExample();
        	com.itic.mall.system.hongbaorecord.persistence.model.HongbaoRecordExample.Criteria criteria = example.createCriteria();
        	criteria.andIsEffectiveEqualTo(DBConst.TRUE).andUserIdEqualTo(userId).andProductIdEqualTo(productId);
        	criteria.andStartTimeEqualTo(product.getStartTime());
        	criteria.andStopTimeEqualTo(product.getStopTime());
        	List<HongbaoRecord> list = hongbaoRecordDao.selectByExample(example);
        	if( list.size() > 0 ){
        		result = "1";
        	}
    	}
        return result; 
    }

	public List<String> getIdsLikeOrderNum(String orderNum) {
		return orderDao.getIdsLikeOrderNum(orderNum);
	}

	public String back(Order order, List<OrderProducts> list) {
		//预计收益
		PreMoneyExample example = new PreMoneyExample();
		com.itic.mall.system.premoney.persistence.model.PreMoneyExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andOrderIdEqualTo(order.getId());
		
		List<PreMoney> list2 = preMoneyDao.selectByExample(example);
		if( list2.size()>0 ){
			for( PreMoney ttmp :list2 ){
				ttmp.setIsEffective(DBConst.FALSE);
				preMoneyDao.updateByPrimaryKeySelective(ttmp);
				//减少用户的预计收益
				String preMoney = ttmp.getPreMoney();
				String marketUserId = ttmp.getMarketUserId();
				MarketUser user = marketUserDao.selectByPrimaryKey(marketUserId);
				String preProfit = user.getPreProfit();
				preProfit = NumberStringHelper.subtractString(preProfit, preMoney);
				user.setPreProfit(preProfit);
				marketUserDao.updateByPrimaryKeySelective(user);
			}
		}
		//更改订单状态
		orderDao.updateByPrimaryKeySelective(order);
		//改变订单产品
		if( list.size()>0 ){
			for( OrderProducts ttmp :list ){
				ttmp.setStatus("4");
				ttmp.setBackStatus("2");
				orderProductsDao.updateByPrimaryKeySelective(ttmp);
			}
		}
		return SUCCESS;
	}


}